package prometheus

import (
	"sync"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/tluo-github/super-runner/common"
)

/**
	job_collector 提供job数据收集器
*/


var numJobCurrentDesc = prometheus.NewDesc(
	"super_runner_current_jobs",
	"当前正在运行的job 数量",
	[]string{"runner"},
	nil,
)

type JobCollector struct {
	builds   			[]*common.Build
	jobsTotal			*prometheus.CounterVec
	jobsFailTotal 		*prometheus.CounterVec
	jobDurationHistogram *prometheus.HistogramVec
	lock     			sync.Mutex
}

func (jc *JobCollector) buildsCount() int {
	jc.lock.Lock()
	defer jc.lock.Unlock()
	return len(jc.builds)
}

// 开始处理 job,全局累加器+1
func (jc *JobCollector) AddBuild(build *common.Build) {
	jc.lock.Lock()
	defer jc.lock.Unlock()

	jc.builds = append(jc.builds, build)
	jc.jobsTotal.WithLabelValues(common.NAME).Inc()

}
//处理完job,添加耗时直方图数据
func (jc *JobCollector) RemoveBuild(deleteBuild *common.Build) bool {
	jc.lock.Lock()
	defer jc.lock.Unlock()

	jc.jobDurationHistogram.WithLabelValues(common.NAME).Observe(deleteBuild.Duration().Seconds())

	for idx, build := range jc.builds {
		if build == deleteBuild {
			jc.builds = append(jc.builds[0:idx], jc.builds[idx+1:]...)

			return true
		}
	}

	return false
}
// 失败的job
func (jc *JobCollector) FailureBuild()  {
	jc.lock.Lock()
	defer jc.lock.Unlock()
	jc.jobsFailTotal.WithLabelValues(common.NAME).Inc()

}

// Describe implements prometheus.Collector.
// 注册详细子指标
func (jc *JobCollector) Describe(ch chan<- *prometheus.Desc) {
	ch <- numJobCurrentDesc

	jc.jobsTotal.Describe(ch)
	jc.jobsFailTotal.Describe(ch)
	jc.jobDurationHistogram.Describe(ch)
}
// Collect implements prometheus.Collector.
// 获取当前子指标的数据
func (jc *JobCollector) Collect(ch chan<- prometheus.Metric) {

	ch <- prometheus.MustNewConstMetric(
		numJobCurrentDesc,
		prometheus.GaugeValue,
		float64(jc.buildsCount()),
		"runner",
	)

	jc.jobsTotal.Collect(ch)
	jc.jobsFailTotal.Collect(ch)
	jc.jobDurationHistogram.Collect(ch)

}

func NewJobCollector() *JobCollector {
	return &JobCollector{
		jobsTotal: prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Name: "super_runner_jobs_total",
				Help: "已处理jobs总数",
			},
			[]string{"runner"},
		),
		jobsFailTotal: prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Name: "super_runner_failed_jobs_total",
				Help: "失败的job总数",
			},
			[]string{"runner"},
		),
		jobDurationHistogram: prometheus.NewHistogramVec(
			prometheus.HistogramOpts{
				Name:    "super_runner_job_duration_seconds",
				Help:    "处理 jobs 耗时直方图",
				Buckets: []float64{30, 60, 300, 600, 1800, 3600, 7200, 10800, 18000, 36000},
			},
			[]string{"runner"},
		),
	}
}
